/*
Copyright 2011, 2012 Alessandro Magnolo.

This file is part of Backlight Indicator.

Backlight Indicator is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Backlight Indicator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Backlight Indicator.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.magnolo.backlight_indicator;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.support.v4.view.MenuCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

/**
 * @author ale
 *
 */
/**
 * @author ale
 * 
 */
public class Backlight_indicatorActivity extends Activity {
	private static final int TRACKER_DISPATCH_INTERVAL_DEVELOPMENT=3;
	private static final int TRACKER_DISPATCH_INTERVAL_PRODUCTION=20;
	private static final String TRACKING_CODE="UA-150944-10";
	private static final String LOG_TAG="indicatorActivity";
	private static final int DIALOG_ABOUT_ID=0;

	private BacklightReceiver backlightReceiver;
	private GoogleAnalyticsTracker tracker;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String version;
		boolean debuggable; // decides whether the app is in development or in production
		try {
			PackageInfo packageInfo=getPackageManager().getPackageInfo(getPackageName(), 0);
			version=packageInfo.versionName;
			debuggable=(packageInfo.applicationInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE)!=0;
		} catch (NameNotFoundException e) {
			version=e.toString();
			debuggable=false;
		}
		Log.d(LOG_TAG, "oncreate "+getIntent()+" version "+version+" debuggable="+debuggable);

		tracker=GoogleAnalyticsTracker.getInstance();
		tracker.startNewSession(TRACKING_CODE, debuggable ? TRACKER_DISPATCH_INTERVAL_DEVELOPMENT
		   : TRACKER_DISPATCH_INTERVAL_PRODUCTION, this);
		tracker.setDryRun(debuggable);
		tracker.setDebug(debuggable);

		setContentView(R.layout.main);
		// "/sys/devices/platform/pixel_qi_screen_ctrl/state"

		if (backlightReceiver==null) {
			IntentFilter filter=new IntentFilter();
			//filter.addAction(Intent.ACTION_SCREEN_OFF);
			filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); // You can not receive this through components declared in manifests
			filter.addAction(Intent.ACTION_SCREEN_ON); // this too doesn't seem to work if not declared in the manifest
			//filter.addAction(Intent.ACTION_SEARCH_LONG_PRESS); // this is an Activity Action, not a Broadcast Action

			backlightReceiver=new BacklightReceiver();
			registerReceiver(backlightReceiver, filter);
		}

		// Store values between instances here
		//SharedPreferences preferences=getPreferences(MODE_PRIVATE);
		SharedPreferences preferences=getSharedPreferences(BacklightIndicator.PREFERENCE_SHARED_NAME, MODE_PRIVATE);
		if (!preferences.contains(BacklightIndicator.PREFERENCE_MODE)) {
			SharedPreferences.Editor editor=preferences.edit();
			editor.putString(BacklightIndicator.PREFERENCE_MODE, OperatingMode.UPDATE_ICON.toString());
			editor.commit();
		}
		/*
		CheckBox forceCheck=(CheckBox) findViewById(R.id.forceCheck);
		forceCheck.setChecked(preferences.getBoolean(BacklightIndicator.PREFERENCE_FORCE, false));
		*/
		//setSelectedButton();

		// Add a Custom Variable to this pageview
		String varName="Version";
		String varValue=version;
		tracker.setCustomVar(1, varName, varValue);
		// Track a page view. This is probably the best way to track which parts of your application
		// are being used.
		tracker.trackPageView("/onCreate");

		checkIntent();
	}

	private void checkIntent() {
		Intent intent=getIntent();

		if (intent!=null&&intent.getAction()!=null) {
			String action=intent.getAction();

			tracker.trackEvent("Intent", // Category
			   action, // Action
			   BacklightIndicator.checkStatus().toString(), // Label			   
			   0); // Value

			if (action.equals(Intent.ACTION_SEARCH_LONG_PRESS)) {
				tracker.trackPageView("/searchLongPress"); // Track a page view. This is probably the best way to track which parts of your application are being used.
				BacklightIndicator.toggleStatus(getApplicationContext());
				moveTaskToBack(true);
				// finish(); with this, the icon gets canceled
			}
		}
		// doesn't work - setIntent(null); // intent was processed, now I set it to null to avoid finding it againg in the onCreate() in case of screen rotation
	}

	@Override
	protected void onDestroy() {
		Log.d(LOG_TAG, "onDestroy: "+backlightReceiver);

		NotificationManager mNotificationManager=(NotificationManager) getApplicationContext().getSystemService(
		   Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(BacklightIndicator.STATUS_NOTIFICATION_ID);
		if (backlightReceiver!=null) try {
			unregisterReceiver(backlightReceiver);
		} catch (IllegalArgumentException e) {
			if (e.getMessage().contains("Receiver not registered")) {
				Log.w(LOG_TAG, "unregisterReceiver: "+e);
			} else {// unexpected, re-throw
				throw e;
			}
		}

		// Stop the tracker when it is no longer needed.
		tracker.dispatch();
		tracker.stopSession();

		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		/*Log.d(LOG_TAG, "onNewIntent: "+backlightReceiver+" equals="+intent.equals(getIntent()));
		Log.d(LOG_TAG, "intent: "+intent.getAction()+" getIntent="
		   +(getIntent()!=null ? getIntent().getAction() : "nullo"));*/
		setIntent(intent); // I have to register the new event
		checkIntent();
	}

	/*
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d(LOG_TAG, "onpause");
	}*/

	@Override
	protected void onResume() {
		super.onResume();
		//Log.d(LOG_TAG, "onresume");
		updateDisplay();
		BacklightIndicator.updateIndicator(getApplicationContext(), "resume");
	}

	public void updateClick(View view) {
		if (view.getId()==R.id.updateButton) {
			updateDisplay();
		}
	}

	private void about() {
		tracker.trackPageView("/about");
		showDialog(DIALOG_ABOUT_ID);
	}

	private void exit() {
		tracker.trackPageView("/exit");
		/* this was moved in onDestroy
		NotificationManager mNotificationManager=(NotificationManager) getApplicationContext().getSystemService(
		   Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancel(BacklightIndicator.STATUS_NOTIFICATION_ID);
		if (backlightReceiver!=null) try {
			unregisterReceiver(backlightReceiver);
		} catch (IllegalArgumentException e) {
			if (e.getMessage().contains("Receiver not registered")) {
				Log.w(LOG_TAG, "unregisterReceiver: "+e);
			} else {// unexpected, re-throw
				throw e;
			}
		}
		*/
		finish();
	}

	/**
	 * Updates the selected state of the mode buttons.
	 */
	private void setSelectedButton() {
		SharedPreferences preferences=getSharedPreferences(BacklightIndicator.PREFERENCE_SHARED_NAME, MODE_PRIVATE);
		String prefModeString=preferences.getString(BacklightIndicator.PREFERENCE_MODE,
		   OperatingMode.UPDATE_ICON.toString());
		OperatingMode prefMode=OperatingMode.valueOf(prefModeString);
		ImageButton forceOnButton=(ImageButton) findViewById(R.id.forceOnButton);
		ImageButton forceOffButton=(ImageButton) findViewById(R.id.forceOffButton);
		ImageButton updateIconButton=(ImageButton) findViewById(R.id.updateIconButton);
		forceOnButton.setSelected(prefMode==OperatingMode.FORCE_ON);
		forceOffButton.setSelected(prefMode==OperatingMode.FORCE_OFF);
		updateIconButton.setSelected(prefMode==OperatingMode.UPDATE_ICON);
	}

	/**
	 * Called when a mode button is clicked.
	 * 
	 * @param view
	 *           the clicked button
	 */
	public void setClick(View view) {
		BacklightStatus status;

		if (view.getId()==R.id.forceOnButton) status=BacklightStatus.ON;
		else if (view.getId()==R.id.forceOffButton) status=BacklightStatus.OFF;
		else status=BacklightStatus.UNKNOWN;

		tracker.trackEvent("Clicks", // Category
		   "mode", // Action
		   status.toString(), // Label
		   0); // Value

		BacklightIndicator.setStatusAndStorePref(status, getApplicationContext());
		updateDisplay();
	}

	private void updateDisplay() {
		updateDisplayStatus();
		setSelectedButton();
	}

	private void updateDisplayStatus() {
		String text;
		BacklightStatus status=BacklightIndicator.checkStatus();
		switch (status) {
		case OFF:
			text=getString(R.string.status_off);
			break;

		case ON:
			text=getString(R.string.status_on);
			break;

		case UNKNOWN:
			text=getString(R.string.status_unknown);
			break;

		default:
			// this should never happen
			text="unexpected condition";
			break;
		}

		TextView statusText=(TextView) findViewById(R.id.statusText);
		statusText.setText(text);
		//notifyStatusBar(status);
		//BacklightIndicator.notifyStatusBar(getApplicationContext(), "gui");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// constants necessary for the compatibility library
		//				final int SHOW_AS_ACTION_ALWAYS=2;
		final int SHOW_AS_ACTION_IF_ROOM=1;
		//		final int SHOW_AS_ACTION_NEVER=0;
		final int SHOW_AS_ACTION_WITH_TEXT=4;

		MenuInflater inflater=getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		// item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // this requires sdkVersion 11
		MenuCompat.setShowAsAction(menu.findItem(R.id.menu_about), SHOW_AS_ACTION_IF_ROOM|SHOW_AS_ACTION_WITH_TEXT); // this is needed because of the compatibility library
		MenuCompat.setShowAsAction(menu.findItem(R.id.menu_exit), SHOW_AS_ACTION_IF_ROOM|SHOW_AS_ACTION_WITH_TEXT); // this is needed because of the compatibility library

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_about:
			Log.d(LOG_TAG, "about");
			about();
			return true;
		case R.id.menu_exit:
			Log.d(LOG_TAG, "exit");
			exit();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog=null;
		switch (id) {
		case DIALOG_ABOUT_ID:
			try {
				dialog=AboutDialogBuilder.create(this);
			} catch (NameNotFoundException e) {
				Log.e(LOG_TAG, "errore durante creazione about dialog "+e);
			}
			break;
		default:
			dialog=null;
		}
		return dialog;
	}
}